/**预设json数据文件读取逻辑
 * 通过表示路由路径 . 表示路由中的 / , # 表示自定义变量
 * 从router-data开始的路径表示路由的前缀
 * TODO 设置默认路由动态提取json文件，根据路由参数生成文件路径并进行读取
 */
var $ = require('../util')
var config = require('../../config.json')
module.exports = function (router) {
  var dataList = []
  var routesList = []
  var dataFile = 'server/routes-data'
  $.walkFile(dataFile, dataList)
  for (let i in dataList) {
    let fl = dataList[i]
    let match = fl.match(/\/[^\/]+$/)
    if (match) {
      let name = match[0]
      let folder = fl.replace(dataFile, '').split('/')
      folder = folder.splice(0, folder.length - 1)
      let nameArr = name.split('.').slice(0, -1)
      let namePath = '/service/:app'
      let varCount = 0
      if (folder && folder.length) {
        namePath += folder.join('/')
      }
      for (let s in nameArr) {
        if (s > 0) namePath += '/'
        if (nameArr[s] === '#') {
          namePath += ':code_' + varCount++
        } else {
          namePath += nameArr[s]
        }
      }
      routesList.push({
        route: namePath,
        path: fl
      })
    }
  }
  // 生成路由函数
  for (let i in routesList) {
    let route = routesList[i]
    router.all(route.route, function (req, res, next) {
      // local_data优先级最高，当不开启local_data时，才使用其他路由
      if (!config.local_data) {
        return next()
      }
      console.log('READ LOCAL DATA: '.cyan + route.path)
      res.send($.readJson(route.path))
    })
  }
}
